<template>
  <div id="app">
    <router-view />
    
    <!-- 使用NutUI 4.x的正确语法 -->
    <nut-tabbar v-if="showTabbar" v-model="activeTab">
      <nut-tabbar-item 
        v-for="item in tabList" 
        :key="item.path" 
        :tab-title="item.text" 
        :icon="item.icon"
        @click="handleTabClick(item)"
      />
    </nut-tabbar>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Home, Category, Cart, My } from '@nutui/icons-vue'

const route = useRoute()
const router = useRouter()

// 当前激活的标签页
const activeTab = ref(0)

// 底部导航栏配置
const tabList = [
  {
    text: '首页',
    icon: Home,
    path: '/'
  },
  {
    text: '分类',
    icon: Category,
    path: '/category'
  },
  {
    text: '购物车',
    icon: Cart,
    path: '/cart'
  },
  {
    text: '我的',
    icon: My,
    path: '/user'
  }
]

// 控制底部导航栏显示
const showTabbar = computed(() => {
  const hideTabbarRoutes = ['/login', '/register', '/product-detail']
  return !hideTabbarRoutes.includes(route.path)
})

// 根据当前路由更新激活的标签页
const updateActiveTab = () => {
  const currentPath = route.path
  const tabIndex = tabList.findIndex(item => {
    // 精确匹配路径，忽略查询参数
    return item.path === currentPath || 
           (currentPath.startsWith(item.path) && item.path !== '/')
  })
  
  if (tabIndex !== -1) {
    activeTab.value = tabIndex
  }
}

// 监听路由变化
watch(() => route.path, updateActiveTab, { immediate: true })

// 标签点击事件
const handleTabClick = (item) => {
  console.log('点击了:', item.text, '目标路径:', item.path, '当前路径:', route.path)
  
  if (item.path !== route.path) {
    try {
      // 使用 Vue Router 进行导航
      router.push(item.path).then(() => {
        console.log('导航成功到:', item.path)
        // 手动更新激活状态
        updateActiveTab()
      }).catch((error) => {
        console.error('导航失败:', error)
        // 如果 router.push 失败，使用 window.location.href 作为备选
        window.location.href = item.path
      })
    } catch (error) {
      console.error('路由错误:', error)
      // 如果有异常，使用 window.location.href 作为备选
      window.location.href = item.path
    }
  } else {
    console.log('已经在当前页面')
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  background-color: #f5f5f5;
}

#app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 50px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 16px 0 12px 16px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-state img {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
  opacity: 0.5;
}
</style>
